<script setup lang="ts">
import { ref, onMounted, computed, watch, onBeforeUnmount } from 'vue'
import { useHomeStore } from '@/stores/homeStore'
import { ElMessage } from 'element-plus'
import {
  Refresh,
  Search,
  Plus,
  Delete,
  Edit,
  Download,
  Filter,
  DataAnalysis,
  Monitor,
  Connection,
  ArrowUp,
  ArrowDown,
  Loading,
  Close,
  HomeFilled,
  Right,
  Clock
} from '@element-plus/icons-vue'
import KeywordMonitor from '@/components/keywords/KeywordMonitor.vue'
import KeywordAnalysis from '@/components/keywords/KeywordAnalysis.vue'

// 获取首页数据状态
const homeStore = useHomeStore()
const loading = ref(false)

// 自动刷新设置
const autoRefresh = ref(false)
const refreshInterval = ref(60) // 默认60秒
let refreshTimer: number | null = null

// 选中的关键词
const selectedKeyword = ref('')
const selectedCategory = ref('')

// 关键词详情对话框
const keywordDetailVisible = ref(false)

// 刷新数据
const refreshData = async () => {
  loading.value = true
  try {
    // 这里可以添加实际的数据刷新逻辑
    await new Promise(resolve => setTimeout(resolve, 1000)) // 模拟API请求
    ElMessage.success('数据刷新成功')
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('数据刷新失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理关键词选择
const handleKeywordSelect = (keyword: string, category: string) => {
  selectedKeyword.value = keyword
  selectedCategory.value = category
  keywordDetailVisible.value = true
}

// 设置自动刷新
watch(autoRefresh, (newVal) => {
  if (newVal && refreshInterval.value > 0) {
    startAutoRefresh()
  } else {
    stopAutoRefresh()
  }
})

watch(refreshInterval, (newVal) => {
  if (autoRefresh.value && newVal > 0) {
    stopAutoRefresh()
    startAutoRefresh()
  }
})

// 开始自动刷新
const startAutoRefresh = () => {
  stopAutoRefresh() // 先清除之前的定时器
  refreshTimer = window.setInterval(() => {
    refreshData()
  }, refreshInterval.value * 1000)
}

// 停止自动刷新
const stopAutoRefresh = () => {
  if (refreshTimer !== null) {
    clearInterval(refreshTimer)
    refreshTimer = null
  }
}

// 当前时间
const currentTime = ref(new Date())
const formattedTime = computed(() => {
  const options: Intl.DateTimeFormatOptions = { 
    year: 'numeric', 
    month: '2-digit', 
    day: '2-digit',
    hour: '2-digit', 
    minute: '2-digit', 
    second: '2-digit',
    hour12: false
  }
  return new Intl.DateTimeFormat('zh-CN', options).format(currentTime.value)
})

// 更新当前时间
const updateTime = () => {
  currentTime.value = new Date()
}

// 组件挂载时
onMounted(() => {
  refreshData()
  // 每秒更新时间
  setInterval(updateTime, 1000)
})

// 组件卸载前清理定时器
onBeforeUnmount(() => {
  stopAutoRefresh()
})
</script>

<template>
  <div class="keyword-monitor-view">
    <!-- 面包屑导航 -->
    <div class="breadcrumb-container">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">
          <el-icon><HomeFilled /></el-icon> 首页
        </el-breadcrumb-item>
        <el-breadcrumb-item>关键词监控</el-breadcrumb-item>
      </el-breadcrumb>
      
      <div class="current-time">
        <el-icon><Clock /></el-icon>
        <span>{{ formattedTime }}</span>
      </div>
    </div>
    
    <!-- 页面标题和控制区 -->
    <div class="page-header">
      <div class="title-section">
        <h1 class="page-title">关键词监控</h1>
        <div class="page-description">
          监控关键词的提及情况，分析情感趋势和来源分布
        </div>
      </div>
      
      <div class="header-actions">
        <div class="refresh-controls">
          <el-switch
            v-model="autoRefresh"
            active-text="自动刷新"
            inactive-text=""
            style="margin-right: 10px;"
          />
          <el-select 
            v-model="refreshInterval" 
            size="small" 
            style="width: 100px; margin-right: 15px;"
            :disabled="!autoRefresh"
          >
            <el-option :value="30" label="30秒" />
            <el-option :value="60" label="1分钟" />
            <el-option :value="300" label="5分钟" />
            <el-option :value="600" label="10分钟" />
          </el-select>
          <el-button type="primary" :icon="Refresh" :loading="loading" @click="refreshData">
            刷新数据
          </el-button>
        </div>
      </div>
    </div>
    
    <!-- 全局加载状态 -->
    <div class="loading-overlay" v-if="loading">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <div class="loading-text">数据加载中...</div>
    </div>
    
    <!-- 关键词监控列表 -->
    <div class="content-container">
      <KeywordMonitor @select-keyword="handleKeywordSelect" />
    </div>
    
    <!-- 关键词详情对话框 -->
    <el-dialog
      v-model="keywordDetailVisible"
      width="85%"
      destroy-on-close
      :fullscreen="false"
      top="5vh"
      class="keyword-detail-dialog"
      :show-close="true"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
    >
      <template #header="{ titleId, titleClass }">
        <div class="dialog-header-content">
          <h4 :id="titleId" :class="titleClass">
            {{ selectedKeyword }}
            <el-tag size="small" effect="plain" style="margin-left: 8px;">{{ selectedCategory }}</el-tag>
          </h4>
        </div>
      </template>
      <KeywordAnalysis 
        v-if="keywordDetailVisible"
        :keyword="selectedKeyword" 
        :category="selectedCategory"
      />
    </el-dialog>
  </div>
</template>

<style scoped>
.keyword-monitor-view {
  padding: 20px;
  height: 100%;
  display: flex;
  flex-direction: column;
  background-color: #f5f7fa;
}

.breadcrumb-container {
  margin-bottom: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.current-time {
  font-size: 13px;
  color: #909399;
  display: flex;
  align-items: center;
  gap: 5px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.title-section {
  display: flex;
  flex-direction: column;
}

.page-title {
  font-size: 22px;
  font-weight: 600;
  color: var(--el-text-color-primary);
  margin: 0;
  margin-bottom: 8px;
}

.page-description {
  font-size: 14px;
  color: #909399;
}

.header-actions {
  display: flex;
  align-items: center;
}

.refresh-controls {
  display: flex;
  align-items: center;
  background-color: #f5f7fa;
  padding: 8px 12px;
  border-radius: 6px;
}

.loading-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(255, 255, 255, 0.7);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.loading-icon {
  font-size: 48px;
  color: var(--el-color-primary);
  animation: rotating 2s linear infinite;
}

.loading-text {
  margin-top: 15px;
  font-size: 16px;
  color: var(--el-text-color-primary);
}

@keyframes rotating {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

.content-container {
  flex: 1;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  overflow: auto;
  min-height: 600px;
}

/* 对话框内容样式 */
:deep(.keyword-detail-dialog) {
  border-radius: 8px;
  overflow: hidden;
}

:deep(.keyword-detail-dialog .el-dialog__header) {
  border-bottom: 1px solid #ebeef5;
  padding: 15px 20px;
  margin-right: 0;
  background-color: #f5f7fa;
}

.dialog-header-content {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
}

.dialog-header-content h4 {
  margin: 0;
  font-size: 18px;
  font-weight: 500;
  display: flex;
  align-items: center;
}

:deep(.keyword-detail-dialog .el-dialog__body) {
  padding: 20px;
  max-height: calc(85vh - 120px);
  overflow-y: auto;
}

:deep(.keyword-detail-dialog .el-dialog__footer) {
  border-top: 1px solid #ebeef5;
  padding: 15px 20px;
}
</style> 